#!/usr/bin/env python
import platform, os, sys

Import("env")
Import("env_modules")
env_module = env_modules.Clone()
JS_ENGINE = "quickjs"
TOOLS = "editor" == env_module["target"]

if env["platform"] == "windows":
    if env["use_mingw"]:
        env.Append(LIBS=["pthread"])


def open_file(path, mode):
    if platform.python_version() > "3":
        return open(path, mode, encoding="utf8")
    else:
        return open(path, mode)


def dump_text_file_to_cpp(file):
    source = open_file(file, "r").read()
    lines = source.split("\n")
    source = ""
    length = len(lines)
    for i in range(length):
        line = lines[i].replace('"', '\\"')
        line = '\t"' + line + '\\n"'
        if i < length - 1:
            line += "\n"
        source += line
    return source


if JS_ENGINE == "quickjs":
    import generate_builtin_api

    generate_builtin_api.generate_api_json(os.path.join(GetLaunchDir(), "modules", os.path.basename(os.getcwd())))
    import thirdparty.quickjs.builtin_binding_generator

    thirdparty.quickjs.builtin_binding_generator.generate_builtin_bindings()
    version = open("thirdparty/quickjs/quickjs/VERSION.txt", "r").read().split("\n")[0]
    quickjs_env = env_modules.Clone()
    quickjs_env.Append(CPPDEFINES={"QUICKJS_CONFIG_VERSION": '"' + version + '"'})
    quickjs_env.Append(CPPDEFINES=["CONFIG_BIGNUM"])
    if "release" not in (quickjs_env["target"] or ""):
        quickjs_env.Append(CPPDEFINES={"DUMP_LEAKS": 1})
        # TODO: Fix debugger
        # quickjs_env.Append(CPPDEFINES={"QUICKJS_WITH_DEBUGGER": 1})
    quickjs_env.Append(CPPPATH=["thirdparty/quickjs/quickjs"])
    quickjs_env.Append(CPPPATH=["thirdparty/quickjs"])
    quickjs_env.disable_warnings()
    quickjs_env.add_source_files(env.modules_sources, "thirdparty/quickjs/quickjs_builtin_binder.gen.cpp")
    quickjs_env.add_source_files(env.modules_sources, "thirdparty/quickjs/*.cpp")
    quickjs_env.add_source_files(env.modules_sources, "thirdparty/quickjs/quickjs/*.c")

# Binding script to run at engine initializing
with open("misc/godot.binding_script.gen.cpp", "w") as f:
    text = '/* THIS FILE IS GENERATED DO NOT EDIT */\n#include "../javascript_binder.h"\nString JavaScriptBinder::BINDING_SCRIPT_CONTENT = \n${source};'
    f.write(text.replace("${source}", dump_text_file_to_cpp("misc/binding_script.js")))

sources = [
    "register_types.cpp",
    "javascript_language.cpp",
    "javascript_instance.cpp",
    "javascript.cpp",
    "misc/godot.binding_script.gen.cpp",
]

if TOOLS:
    base_text = (
        '/* THIS FILE IS GENERATED DO NOT EDIT */\n#include "editor_tools.h"\nString JavaScriptPlugin::{} = \n{};'
    )
    tool_fns = {
        "editor/godot.d.ts.gen.cpp": (
            "BUILTIN_DECLARATION_TEXT",
            dump_text_file_to_cpp("misc/godot.d.ts"),
        ),
        "editor/tsconfig.json.gen.cpp": (
            "TSCONFIG_CONTENT",
            dump_text_file_to_cpp("misc/tsconfig.json"),
        ),
        "editor/decorators.ts.gen.cpp": (
            "TS_DECORATORS_CONTENT",
            dump_text_file_to_cpp("misc/decorators.ts"),
        ),
        "editor/package.json.gen.cpp": (
            "PACKAGE_JSON_CONTENT",
            dump_text_file_to_cpp("misc/package.json"),
        ),
    }
    for fn, subs in tool_fns.items():
        with open_file(fn, "w") as fh:
            fh.write(base_text.format(*subs))
        env_module.add_source_files(env.modules_sources, fn)


env_module.Append(CPPPATH=["#modules/javascript"])
env_module.add_source_files(env.modules_sources, sources)

if env.editor_build:
    env_module.add_source_files(env.modules_sources, "editor/workarounds/*.cpp")
    env_module.add_source_files(env.modules_sources, "editor/*.cpp")
